<template>
  <div>
    <div>
      <el-divider />
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="form.taskName"
              placeholder="请输入任务名称"
              style="width: 204px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迁移类型" prop="migrationType">
            <el-select v-model="form.migrationType" :disabled="form.isHiddenValu" placeholder="请选择迁移类型" clearable filterable @change="changeMigrationType">
              <el-option
                v-for="item in migrationTypeList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
                :disabled="!item.enabled"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="脚本选择方式" prop="scriptSelectType">
            <el-radio-group v-model="form.scriptSelectType">
              <el-radio-button label="直连">直连</el-radio-button>
              <el-radio-button label="导入">导入</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row v-if="form.scriptSelectType === '直连'">
        <el-col :span="12">
          <el-form-item label="源数据源" prop="sourceConnPkId">
            <el-select v-model="form.sourceConnPkId" clearable filterable placeholder="请选择" @change="dataSourceConnChange">
              <el-option
                v-for="item in sourceConnList"
                :key="item.pkId"
                :label="item.sourceName"
                :value="item.pkId"
              />
            </el-select>
          </el-form-item>
          <el-button
            class="bordered-button"
            :disabled="form.sourceConnPkId === null || form.database === null"
            size="medium"
            type="text"
            @click="showScripList"
          >选择需要测试的脚本
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col v-if="form.scriptSelectType === '导入'">
          <el-form-item label="操作">
            <el-button
              style="float: left"
              size="mini"
              type="primary"
              icon="el-icon-download"
              @click="templateDownload"
            >
              模板下载
            </el-button>
            <el-upload
              ref="uploadExcel"
              style="float: left"
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
            >
              <div>
                <el-button
                  style="float: left; margin-left: 5px"
                  size="mini"
                  type="primary"
                  icon="el-icon-upload2"
                >
                  文件上传
                </el-button>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="8">
          <el-input v-model.trim="queryName" placeholder="请输入脚本名称" clearable @keyup.native.enter="toQuery" />
        </el-col>
        <el-button
          class="filter-item"
          size="mini"
          style="margin-left: 5px"
          type="success"
          icon="el-icon-search"
          @click="toQuery"
        >搜索
        </el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置
        </el-button>
        <el-button class="filter-item" type="danger" icon="el-icon-delete" size="mini" @click="removeTestScript">删除
        </el-button>
      </el-row>
      <el-table :data="form.testScriptList" border max-height="240" @selection-change="testScriptHandleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="scriptName" label="脚本名称" />
      </el-table>
    </div>

    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="isSelectScriptFlag"
      title="选择测试脚本"
      width="1000px"
    >
      <div>
        <el-transfer
          v-if="isSelectScriptFlag"
          v-model="selectScriptList"
          filterable
          :titles="['待选-测试脚本清单', '已选-测试脚本清单']"
          :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}'}"
          :props="{key: 'pkId', label: 'convertFileName'}"
          :data="scriptList"
        >
          <span slot-scope="{ option }">
            <el-tooltip
              class="item"
              :content="option.convertFileName"
              placement="top"
            >
              <span>{{ option.convertFileName }}</span>
            </el-tooltip>
          </span>
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center">
        <el-button type="primary" style="margin-right: 30px" @click="submitSelectScript">同意</el-button>
        <el-button @click="isSelectScriptFlag=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import convertScriptListApi from '@/api/script/transfer/script-convert-target-list'
import { downloadFile } from '@utils'
import { crunDate } from '@utils/data'
import CRUD from '@crud/crud'
import dataSourceApi from '@/api/metadata/dataSource'
import scriptConvertTaskApi from '@/api/script/transfer/script-convert-task'

export default {
  name: 'ScriptConvertList',
  model: {
    prop: 'form',
    event: 'changes'
  },
  props: {
    form: {
      required: true,
      type: Object
    },
    crud: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      isSelectScriptFlag: false,
      migrationTypeList: [],
      selectScriptList: [],
      scriptList: [],
      sourceConnList: [],
      sourceDatabaseList: [],
      queryName: null,
      selectTestScriptName: [],
      tempTestScriptList: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      this.initMigrationTypeList()
      if (this.crud.status.add) {
        this.form.taskName = `脚本测试-${crunDate()}`
        const data = await dataSourceApi.findDefaultSource()
        const sourceDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'source')
        const targetDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'target')
        const migrationType = (sourceDefault === undefined ? '' : sourceDefault.sourceType) + '-' + (targetDefault === undefined ? '' : targetDefault.sourceType)
        if (this.migrationTypeList.some(item => item.name === migrationType && item.enabled === true)) {
          this.form.migrationType = migrationType
          this.changeMigrationType(this.form.migrationType)
          this.form.sourceConnPkId = sourceDefault === undefined ? '' : sourceDefault.pkId
          this.form.targetConnPkId = targetDefault === undefined ? '' : targetDefault.pkId
        }
        if (this.form.sourceConnPkId) {
          await this.dataSourceConnChange(this.form.sourceConnPkId)
        }
      }
    },
    changeMigrationType(val) {
      const sourceTypes = val.split('-')
      this.initSourceConnList(sourceTypes[0])
      // this.initTargetConnList(sourceTypes[1])
      this.form.database = ''
    },
    // 获取数据源信息
    initSourceConnList(sourceType) {
      const params = { serverType: 'SOURCE', status: 'ENABLE', sourceType: sourceType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.sourceConnList = res.content
        }
      })
    },
    initTargetConnList(targetType) {
      const params = { serverType: 'TARGET', sourceType: targetType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.targetConnList = res.content
        }
      })
    },
    initMigrationTypeList() {
      scriptConvertTaskApi.getMigrationTypeInfos().then(res => {
        this.migrationTypeList = res
      })
    },
    dataSourceConnChange(sourceConnPkId) {
      this.form.database = ''
      this.sourceDatabaseList = []
      if (sourceConnPkId) {
        dataSourceApi.schemas(sourceConnPkId).then(res => {
          this.sourceDatabaseList = res
        })
      }
    },
    showScripList() {
      this.resetQuery()
      this.$emit('loadingChange', true)
      const param = {
        size: 500,
        emptyTestStatus: 'SUCCESS',
        sourceConnPkId: this.form.sourceConnPkId,
        database: this.form.database
      }
      convertScriptListApi.findLatestSuccess(param).then(data => {
        this.$emit('loadingChange', false)
        this.scriptList = data.content
        this.initselectScriptList()
        this.isSelectScriptFlag = true
      }).catch(() => {
        this.$emit('loadingChange', false)
        this.crud.notify('获取转换脚本清单失败！', CRUD.NOTIFICATION_TYPE.ERROR)
      })
    },
    initselectScriptList() {
      this.selectScriptList = []
      this.scriptList.forEach(item => {
        this.form.testScriptList.forEach(item2 => {
          if (item2.scriptConvertListPkId === item.pkId) {
            this.selectScriptList.push(item.pkId)
          }
        })
      })
    },
    toQuery() {
      if (this.queryName === undefined || this.queryName === null || this.queryName === '') {
        this.resetQuery()
      } else {
        this.tempTestScriptList = JSON.parse(JSON.stringify(this.form.testScriptList))
        this.form.testScriptList = this.form.testScriptList.filter((item) => {
          return item.scriptName.toUpperCase().includes(this.queryName.toUpperCase())
        })
      }
    },
    resetQuery() {
      this.queryName = null
      if (this.tempTestScriptList !== undefined && this.tempTestScriptList.length > 0) {
        this.form.testScriptList = JSON.parse(JSON.stringify(this.tempTestScriptList))
        this.tempTestScriptList = []
      }
    },
    // 记录选择的测试脚本
    testScriptHandleSelectionChange(val) {
      this.selectTestScriptName = []
      val.forEach(item => {
        this.selectTestScriptName.push(item.scriptConvertListPkId)
      })
    },
    // 删除测试脚本
    removeTestScript() {
      this.selectTestScriptName.forEach(removeId => {
        this.form.testScriptList.forEach((item, index) => {
          if (removeId === item.scriptConvertListPkId) {
            this.form.testScriptList.splice(index, 1)
          }
        })
        this.selectScriptList.forEach((id, index) => {
          if (removeId === id) {
            this.selectScriptList.splice(index, 1)
          }
        })
      })
    },
    submitSelectScript() {
      const scriptConvertListPkIds = this.form.testScriptList.map(item => {
        return item.scriptConvertListPkId
      })
      this.isSelectScriptFlag = false
      this.scriptList.forEach(item => {
        if (this.selectScriptList.includes(item.pkId) && !scriptConvertListPkIds.includes(item.pkId)) {
          const data = { pkId: null, taskPkId: null, scriptConvertListPkId: item.pkId, scriptName: item.convertFileName, status: 'TODO' }
          this.form.testScriptList.push(data)
        }
      })
    },
    // 文件上传操作
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // 移除所上传文件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    templateDownload() {
      this.crud.downloadLoading = true
      convertScriptListApi.downloadTemplate().then(result => {
        downloadFile(result, '上传模板')
        this.crud.downloadLoading = false
      }).catch(() => {
        this.crud.downloadLoading = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 400px !important;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:last-child {
  margin-left: 0px;
}
</style>
